package com.jt.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jt.mapper.UserMapper;
import com.jt.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

@Component
public class UserServiceImpl implements UserService{
    @Autowired
    private UserMapper userMapper;


    @Override
    public List<User> findAll() {
        return userMapper.selectList(null);
    }

    @Override//使用自己写的sql及方法实现
    public User findUserById(Integer id) {
        return userMapper.findUserById(id);
    }

    @Override//调用MP方法实现
    public User findUserById2(Integer id) {

        return userMapper.selectById(id);
    }

    @Override
    /*1.通过对象封装数据
        User user = new User();
        user.setName("小乔").setSex("女");
        //2.构建条件构造器 根据对象中不为null的属性充当where条件!即where name="小乔" and sex="女"
        QueryWrapper<User> queryWrapper = new QueryWrapper(user);
        //3.根据条件构造器 实现数据查询
        List<User> userList = userMapper.selectList(queryWrapper);
        System.out.println(userList);*/
    public List<User> findByNameSex(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper(user);
        return userMapper.selectList(wrapper);
    }

    @Override
    public List<User> findUserByNA(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("name", user.getName())
                .gt("age", user.getAge());
        userMapper.selectList(wrapper);
        return userMapper.selectList(wrapper);
    }

    @Override
    public List<User> findUserByIds(Integer[] ids) {
        List asList = Arrays.asList(ids);
        return userMapper.selectBatchIds(asList);
    }

    @Override
    public List<User> getUserBySA(User user) {
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("sex", user.getSex())
                .gt("age", user.getAge());
        return userMapper.selectList(wrapper);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public void saveUser(User user) {
        userMapper.insert(user);
    }

    @Override
    public void updateUser(User user) {
//        QueryWrapper wrapper = new QueryWrapper();
//        wrapper.eq("id", 240);
//        userMapper.update(user,wrapper );
        userMapper.updateById(user);
    }

    @Override
    public void updateUserByName(User user, String whereName) {
      /* QueryWrapper和UpdateWrapper功能一样，可以混合用*/
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("name", whereName);
        userMapper.update(user,wrapper );
    }

    @Override
    public void updateUserById(User user) {
        userMapper.updateById(user);
    }

}
